# ==============================================================================
# DESCRIPTION ----
# ==============================================================================

# This script performs event studies of firm stock returns on the day of hiring 
# announcements of former vice-ministers. 

# ==============================================================================
# PREAMBLE, LIBRARIES, AND IMPORT ----
# ==============================================================================

#### Preamble ####
encoding = "UTF-8"
set.seed(999)

#### Libraries ####
library(tidyverse)
library(tidyquant)
library(eventstudies)

#### Import ####
# Import amakudari data
amakudari <- read_csv("data/amakudata.csv")

# ==============================================================================
# FILTER DATA TO VICE-MINISTERS ONLY ----
# ==============================================================================

# Filter data to vice-minister and assistant vice-minister retirements only
all <- amakudari %>% 
  filter(
    firm_type2_en == "Stock",
    position_level == "Vice-Minister" | 
    position_level == "Assistant Vice-Minister",
    #ministry != "Cabinet office",
    ministry != "Police",
    tse_code != -99,
    tse_code != 99) %>%
  select(date_ret, name, position_level, ministry_short, 
         firm_dest, firm_dest_en, post_dest, tse_code)

avm <- all %>% filter(position_level == "Assistant Vice-Minister")
vm <- all %>% filter(position_level == "Vice-Minister")

# ==============================================================================
# RETREIVE FINANCIAL DATA FROM YAHOO FINANCE ----
# ==============================================================================

# Create list of tickers
tickers <- unique(all$tse_code)
tickers <- paste(tickers, "T", sep = ".")

# Add some stock codes manually to increase sample of events
tickers <- append(tickers,'1812.T')
tickers <- append(tickers,'8411.T')

# Add Nikkei 225 Index and TOPIX for market model
tickers <- append(tickers, "^N225")

# Retrieve financial data from Yahoo Finance using tidyquant
prices <- tq_get(x = tickers,
                 get = "stock.prices",
                 from = "2009-01-01",
                 to = "2019-12-31")
# write_csv(prices, file = "data/stock_prices.csv") In case tidyquant breaks...

# Add percentage change column and transform long to wide
prices_long <- prices %>%
  group_by(symbol) %>% 
  mutate(pct_change = (adjusted/lag(adjusted) - 1) * 100) %>%
  ungroup() %>%
  filter(!is.na(pct_change)) %>%
  distinct(symbol, date, pct_change) %>%
  select(symbol, date, pct_change) %>%
  pivot_wider(names_from = symbol, values_from = pct_change)

# ==============================================================================
# ADD EVENT DATES FROM NEWS REPORTS TO ALL RETIREMENTS ----
# ==============================================================================

#### Import coded event dates ####
event_dates_avm <- read_csv("data/event_dates_avm.csv")
event_dates_vm <- read_csv("data/event_dates_vm.csv")
event_dates <- rbind(event_dates_avm, event_dates_vm) %>%
  rename(firm = firm_dest_english)

#### Create separate dataframes for each category #### 
# Create separate dataframe of outside directors
director <- event_dates %>% 
  filter((position == "internal director" | position == "outside director") & !is.na(when))

# Create separate dataframe of vice ministerial consultants
advisor_vm <- event_dates %>% 
  filter(position != "outside director" & !is.na(when)) %>%
  filter(position_level == "Vice-Minister" & !is.na(when))

# Create separate dataframe of all internal hires
internal <- event_dates %>% 
  filter((position == "advisor" | position == "executive" | position == "manager") & !is.na(when)) 

# Create separate dataframe of METI 
meti <- event_dates %>% filter(ministry_short == "METI" & !is.na(when))

# Create separate dataframe of MOF 
mof <- event_dates %>% filter(ministry_short == "MOF" & !is.na(when))

# Create separate dataframe of non-METI 
other_ministry <- event_dates %>% filter(ministry_short != "METI" & !is.na(when))

# Place in R date-time format: all
event_dates <- event_dates %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

event_dates <- as.data.frame(event_dates)

# Place in R date-time format: outside directors
director_event_dates <- director %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

director_event_dates <- as.data.frame(director_event_dates)

# Place in R date-time format: vice ministerial consultants
advisor_vm_event_dates <- advisor_vm %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

advisor_vm_event_dates <- as.data.frame(advisor_vm_event_dates)

# Place in R date-time format: internal
internal_event_dates <- internal %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

internal_event_dates <- as.data.frame(internal_event_dates)

# Place in R date-time format: meti
meti_event_dates <- meti %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

meti_event_dates <- as.data.frame(meti_event_dates)

# Place in R date-time format: MOF
mof_event_dates <- mof %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

mof_event_dates <- as.data.frame(mof_event_dates)

# Place in R date-time format: non-meti
other_ministry_event_dates <- other_ministry %>% 
  mutate(when = as.Date(when)) %>%
  filter(!is.na(when)) %>%
  select(ticker, when) %>%
  rename(name = ticker)

other_ministry_event_dates <- as.data.frame(other_ministry_event_dates)

# ==============================================================================
# PERFORM EVENT STUDIES ----
# ==============================================================================

# Convert stock data to zoo time series object
prices_ts <- prices_long %>% mutate(`^N225` = ifelse(is.na(`^N225`), 0, `^N225`))
prices_ts <- read.zoo(prices_ts)

# Define event window
event_window = 8

#### Market model: all appointments  ####
mm_all <- eventstudy(firm.returns = prices_ts,
                     event.list = event_dates,
                     event.window = event_window,
                     type = "marketModel",
                     to.remap = TRUE,
                     remap = "cumsum",
                     inference = TRUE,
                     inference.strategy = "bootstrap",
                     model.args = list(market.returns = prices_ts$`^N225`))

#### Market model: directors  ####
mm_director <- eventstudy(firm.returns = prices_ts,
                          event.list = director_event_dates,
                          event.window = event_window,
                          type = "marketModel",
                          to.remap = TRUE,
                          remap = "cumsum",
                          inference = TRUE,
                          inference.strategy = "bootstrap",
                          model.args = list(market.returns = prices_ts$`^N225`))

#### Market model: internal hires ####
mm_internal <- eventstudy(firm.returns = prices_ts,
                          event.list = internal_event_dates,
                          event.window = event_window,
                          type = "marketModel",
                          to.remap = TRUE,
                          remap = "cumsum",
                          inference = TRUE,
                          inference.strategy = "bootstrap",
                          model.args = list(market.returns = prices_ts$`^N225`))

#### Market model: vice-ministerial consultants ####
mm_advisor_vm <- eventstudy(firm.returns = prices_ts,
                         event.list = advisor_vm_event_dates,
                         event.window = event_window,
                         type = "marketModel",
                         to.remap = TRUE,
                         remap = "cumsum",
                         inference = TRUE,
                         inference.strategy = "bootstrap",
                         model.args = list(market.returns = prices_ts$`^N225`))

#### Market model: METI appointments  ####
mm_meti <- eventstudy(firm.returns = prices_ts,
                      event.list = meti_event_dates,
                      event.window = event_window,
                      type = "marketModel",
                      to.remap = TRUE,
                      remap = "cumsum",
                      inference = TRUE,
                      inference.strategy = "bootstrap",
                      model.args = list(market.returns=prices_ts$`^N225`))

#### Market model: Other ministry appointments  ####
mm_other_ministry <- eventstudy(firm.returns = prices_ts,
                      event.list = other_ministry_event_dates,
                      event.window = event_window,
                      type = "marketModel",
                      to.remap = TRUE,
                      remap = "cumsum",
                      inference = TRUE,
                      inference.strategy = "bootstrap",
                      model.args = list(market.returns=prices_ts$`^N225`))

# ==============================================================================
# PLOT RESULTS ----
# ==============================================================================

##### Convert to tibble and clean data ####
mm_all <- as_tibble(mm_all$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "All")

mm_director <- as_tibble(mm_director$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "Directors")

mm_advisor_vm <- as_tibble(mm_advisor_vm$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "Advisors")

mm_internal <- as_tibble(mm_internal$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "Internal hires")

mm_meti <- as_tibble(mm_meti$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "METI")

mm_other_ministry <- as_tibble(mm_other_ministry$result) %>%
  rename(mean = Mean, ci_low = `2.5%`, ci_high = `97.5%`) %>%
  mutate(event_day = row_number() - event_window) %>%
  mutate(id = "Other ministries")

mm <- rbind(mm_all, mm_director, mm_internal) %>%
  mutate(id = fct_relevel(id, "All", "Directors", "Internal hires"))

mm_ministries <- rbind(mm_meti, mm_other_ministry) %>%
  mutate(id = fct_relevel(id, "METI", "Other ministries"))

#### Plot cumulate abnormal returns and 95% confidence intervals: main results ####
mm_plot = 
  ggplot(mm) +
  geom_line(aes(x = event_day, y = ci_low), linetype = "dashed") +
  geom_line(aes(x = event_day, y = ci_high), linetype = "dashed") +
  geom_ribbon(aes(x = event_day, ymin = ci_low, ymax = ci_high), 
              fill="steelblue2", alpha = 0.2) +
  geom_point(aes(x = event_day, y = mean)) +
  geom_line(aes(x = event_day, y = mean)) +
  geom_vline(xintercept = 0, linetype = "solid") +
  geom_hline(yintercept = 0, linetype = "solid") +
  xlab("Event day") + 
  ylab("Cumulative abnormal returns (%)") + 
  scale_x_continuous(limits = c((event_window*-1)-1, event_window+1), 
                     breaks=seq((event_window*-1)-1, event_window+1, 2)) +
  scale_y_continuous(limits = c(-6, 6), breaks=seq(-6, 6, 2)) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text=element_text(size = 10)) +
  theme(axis.text.x = element_text(size = 10)) +
  theme(legend.position = "none")

mm_plot = mm_plot + facet_wrap(vars(id), nrow = 3)

# FIGURE 6: Output ggplot
ggsave("figures/6_event_study.pdf", height = 6, width = 6)

#### Plot cumulate abnormal returns and 95% confidence intervals: vice-ministerial advisors ####
mm_plot = 
  ggplot(mm_advisor_vm) +
  geom_line(aes(x = event_day, y = ci_low), linetype = "dashed") +
  geom_line(aes(x = event_day, y = ci_high), linetype = "dashed") +
  geom_ribbon(aes(x = event_day, ymin = ci_low, ymax = ci_high), 
              fill="steelblue2", alpha = 0.2) +
  geom_point(aes(x = event_day, y = mean)) +
  geom_line(aes(x = event_day, y = mean)) +
  geom_vline(xintercept = 0, linetype = "solid") +
  geom_hline(yintercept = 0, linetype = "solid") +
  xlab("Event day") + 
  ylab("Cumulative abnormal returns (%)") + 
  scale_x_continuous(limits = c(-8, 8), breaks=seq(-8, 8, 2)) +
  scale_y_continuous(limits = c(-6, 12), breaks=seq(-6, 12, 2)) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text=element_text(size = 10)) +
  theme(axis.text.x = element_text(size = 10)) +
  theme(legend.position = "none")

# FIGURE A27: Output ggplot
ggsave("figures/a27_event_study_advisor_vm.pdf", height = 3, width = 6)

#### Plot cumulate abnormal returns and 95% confidence intervals: METI ####
mm_plot = 
  ggplot(mm_ministries) +
  geom_line(aes(x = event_day, y = ci_low), linetype = "dashed") +
  geom_line(aes(x = event_day, y = ci_high), linetype = "dashed") +
  geom_ribbon(aes(x = event_day, ymin = ci_low, ymax = ci_high), 
              fill="steelblue2", alpha = 0.2) +
  geom_point(aes(x = event_day, y = mean)) +
  geom_line(aes(x = event_day, y = mean)) +
  geom_vline(xintercept = 0, linetype = "solid") +
  geom_hline(yintercept = 0, linetype = "solid") +
  xlab("Event day") + 
  ylab("Cumulative abnormal returns (%)") + 
  scale_x_continuous(limits = c(-8, 8), breaks=seq(-8, 8, 2)) +
  scale_y_continuous(limits = c(-6, 6), breaks=seq(-6, 6, 2)) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text=element_text(size = 10)) +
  theme(axis.text.x = element_text(size = 10)) +
  theme(legend.position = "none")

mm_plot = mm_plot + facet_wrap(vars(id), nrow = 2)

# FIGURE A28: Output ggplot
ggsave("figures/a28_event_study_meti.pdf", height = 4, width = 6)

# ==============================================================================
# TABULAR RESULTS ----
# ==============================================================================

# Output tables: formatting ----------------------------------------------------
table_format <- function(data) {
  data %>%
    mutate(across(ci_low:ci_high, ~round(., 2))) %>%
    select(`Event Day` = event_day, Estimate = mean, 
           `95% CI lower` = ci_low, `95% CI upper` = ci_high)
}

mm_all <- table_format(mm_all)
mm_director <- table_format(mm_director)
mm_advisor_vm <- table_format(mm_advisor_vm)
mm_internal <- table_format(mm_internal)
mm_meti <- table_format(mm_meti)
mm_other_ministry <- table_format(mm_other_ministry)

# Output to LaTeX using stargazer ----------------------------------------------
# TABLE A14: all
stargazer::stargazer(
  mm_all, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns from assistant vice-minister and vice-minister appointments",
  label = "tab: event_study_all",
  notes = paste("Note: Total events =", length(event_dates$when)),
  out = "tables/a14_event_study.tex")

# TABLE A15: Directors
stargazer::stargazer(
  mm_director, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns from assistant vice-minister and vice-minister appointments, outside director appointments",
  label = "tab: event_study_director",
  notes = paste("Note: Total events =", length(director_event_dates$when)),
  out = "tables/a15_event_study_director.tex")

# TABLE A16: Internal
stargazer::stargazer(
  mm_internal, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns from assistant vice-minister and vice-minister appointments, internal appointments",
  label = "tab: event_study_internal",
  notes = paste("Note: Total events =", length(internal_event_dates$when)),
  out = "tables/a16_event_study_internal.tex")

# TABLE A17: Consultants
stargazer::stargazer(
  mm_advisor_vm, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns after hiring former vice-ministers as consultants",
  label = "tab: event_study_advisor_vm",
  notes = paste("Note: Total events =", length(advisor_vm_event_dates$when)),
  out = "tables/a17_event_study_advisor_vm.tex")

# TABLE A18: METI
stargazer::stargazer(
  mm_meti, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns from assistant vice-minister and vice-minister appointments, METI appointments",
  label = "tab: event_study_meti",
  notes = paste("Note: Total events =", length(meti_event_dates$when)),
  out = "tables/a18_event_study_meti.tex")

# TABLE A19: Ministries other than METI
stargazer::stargazer(
  mm_other_ministry, summary = FALSE, digits = 2, rownames = FALSE, font.size = "footnotesize",
  title = "Cumulative abnormal returns from assistant vice-minister and vice-minister appointments, appointments from ministries other than METI",
  label = "tab: event_study_other",
  notes = paste("Note: Total events =", length(other_ministry_event_dates$when)),
  out = "tables/a19_event_study_other.tex")
